﻿using System;
using EpiNEXT.Services;

namespace EpiNEXT.Services.Validation.Functions
{
    public sealed class RecordCount : FunctionBase
    {
        public RecordCount()
            : base()
        {
        }

        public override object Execute(Record record)
        {
            if (Parameters.Count == 0)
            {
                return record.Form.Records.Count;
            }
            else
            {
                string formTitle = Parameters[0].GetValue(record).ToString();

                DataEntryInstrument form = null;

                foreach (Form iForm in record.Form.Owner.Forms)
                {
                    if (iForm.Title.Equals(formTitle, StringComparison.OrdinalIgnoreCase))
                    {
                        form = iForm;
                        break;
                    }
                }

                foreach (DataGridTable iTable in record.Form.Owner.DataGridTables)
                {
                    if (iTable.Title.Equals(formTitle, StringComparison.OrdinalIgnoreCase))
                    {
                        form = iTable;
                        break;
                    }
                }

                return form.Records.Count;
            }
        }
    }
}
